package com.youzi.usercenter.service;

import com.youzi.corazon.common.exception.ServiceException;
import com.youzi.corazon.common.security.Md5Util;
import com.youzi.usercenter.form.ModifyPasswordForm;
import com.youzi.usercenter.mapper.TUserMapper;
import com.youzi.usercenter.model.TUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created by tanxl on 2017-12-15.
 */
@Service
@Transactional
public class UserService {

    @Autowired
    TUserMapper userMapper;

    public TUser findByUsername(String username) {
        return userMapper.findByUsername(username);
    }

    public void addUser(TUser user) {
        userMapper.insertSelective(user);
    }

    public void update(TUser user) {
        userMapper.updateById(user);
    }

    public void updatePassword(ModifyPasswordForm form){
        TUser user = userMapper.selectByPrimaryKey(form.getUserId());
        if(user == null){
            throw new ServiceException("用户不存在");
        }

        String oldPassword = Md5Util.md5(form.getOldPassword());
        if(!oldPassword.equals(user.getPassword())){
            throw new ServiceException("密码验证错误");
        }
        user.setPassword(Md5Util.md5(form.getNewPassword()));
        userMapper.updatePassword(user);
    }
}
